package net.gyapp.markim.module.contact;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.easyder.wrapper.base.view.WrapperSwipeActivity;
import com.easyder.wrapper.core.model.BaseVo;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.entity.ConversationEntity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.contact.adapter.SearchResultAdapter;
import net.gyapp.markim.module.contact.vo.GroupListVo;
import net.gyapp.markim.module.message.ConversationActivity;
import net.gyapp.markim.utils.RequestParams;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import me.winds.widget.usage.TitleView;

/**
 * Auther:  winds
 * Email:   heardown@163.com
 * Date:    2018/8/12.
 * Desc:
 */
public class GroupAddActivity extends WrapperSwipeActivity<CommonPresenter> implements TextView.OnEditorActionListener {

    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.tv_group_num)
    TextView tvGroupNum;
    @BindView(R.id.tv_group_status)
    TextView tvGroupStatus;
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    public static final int TYPE_CREATE_TIME = 1;
    public static final int TYPE_GROUP_NUM = 2;
    public static final int TYPE_GROUP_STATUS = 3;

    public int type = TYPE_CREATE_TIME;

    String keyword;
    SearchResultAdapter adapter;

    public static Intent getIntent(Context context) {
        return new Intent(context, GroupAddActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    }

    public static Intent getIntent(Context context, String keyword) {
        return new Intent(context, GroupAddActivity.class).putExtra("keyword", keyword).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    }


    @Override
    protected int getViewLayout() {
        return R.layout.activity_group_add;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setCenterText("搜索群");
        titleView.setRightImage(R.drawable.msg_scan);
        titleView.title_iv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(GroupAddActivity.getIntent(mActivity));
            }
        });
        getContainerView().setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorFore));
        etInput.setImeActionLabel("搜索", EditorInfo.IME_ACTION_SEARCH);
        etInput.setOnEditorActionListener(this);
        setCateSelected(tvCreateTime);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new SearchResultAdapter();
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                Object item = adapter.getItem(position);
                if (item instanceof GroupListVo.FindGroupsBean) {
                    GroupListVo.FindGroupsBean bean = (GroupListVo.FindGroupsBean) item;
//                    if (bean.groupStatus == 1 || bean.groupStatus == 4) {
//                        applyJoinGroup(((GroupListVo.FindGroupsBean) item).groupNumber);
//                    } else {
                        ConversationEntity entity = ImHelper.generateConversation(bean.groupNumber);
                        if (entity != null) {
                            startActivity(ConversationActivity.getIntent(mActivity, entity));
                        } else {
                            applyJoinGroup(((GroupListVo.FindGroupsBean) item).groupNumber);
                        }
//                    }
                }
            }
        });
    }

    private void applyJoinGroup(String groupNumber) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_JOIN_GROUP, new RequestParams().put("groupNumber", groupNumber).get(), BaseVo.class);
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        keyword = intent.getStringExtra("keyword");
//        if (!TextUtils.isEmpty(keyword)) {
//            searchGroup(keyword);
//        }
        searchGroup(keyword);
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_FIND_USER_GROUP)) {
            processList((GroupListVo) dataVo);
        } else if (url.contains(ApiConfig.API_JOIN_GROUP)) {
            showToast("申请已提交");
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH && v.getId() == R.id.et_input) {
            keyword = etInput.getText().toString();
//            if (!TextUtils.isEmpty(keyword)) {
            searchGroup(keyword);
//            }
        }
        return false;
    }

    private void searchGroup(String s) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_FIND_USER_GROUP, new RequestParams().put("groupName", s == null ? "" : s).put("type", type).get(), GroupListVo.class);
    }

    private void searchGroup() {
        searchGroup(keyword);
    }


    @OnClick({R.id.tv_create_time, R.id.tv_group_num, R.id.tv_group_status})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_create_time:
                type = TYPE_CREATE_TIME;
                setCateSelected(view);
                searchGroup();
                break;
            case R.id.tv_group_num:
                type = TYPE_GROUP_NUM;
                setCateSelected(view);
                searchGroup();
                break;
            case R.id.tv_group_status:
                type = TYPE_GROUP_STATUS;
                setCateSelected(view);
                searchGroup();
                break;
        }
    }


    private void setCateSelected(View view) {
        tvCreateTime.setSelected(view.getId() == R.id.tv_create_time);
        tvGroupNum.setSelected(view.getId() == R.id.tv_group_num);
        tvGroupStatus.setSelected(view.getId() == R.id.tv_group_status);
    }


    private void processList(GroupListVo dataVo) {
        if (dataVo.findGroups != null && dataVo.findGroups.size() > 0) {
//            startActivity(SearchResultActivity.getGroupIntent(mActivity, dataVo.findGroups));
            ArrayList<Object> list = new ArrayList<>();
            list.addAll(dataVo.findGroups);
            adapter.setAdapterData(list);
        } else {
            showToast("未搜索到结果");
        }
    }

}
